//
//  TitlePopAnimate.m
//  SinaWebo
//
//  Created by 王方伟 on 2017/1/17.
//  Copyright © 2017年 亦心. All rights reserved.
//

#import "TitlePopAnimate.h"
#import "TitlePresentationController.h"

@interface TitlePopAnimate ()
@property (assign, nonatomic) BOOL isPresented;
@end

@implementation TitlePopAnimate

- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source{
    TitlePresentationController *presnetVC = [[TitlePresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
    presnetVC.frame = self.frame;
    return presnetVC;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    _isPresented = TRUE;
    if (_block) {
        _block(_isPresented);
    }
    return self;
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    _isPresented = FALSE;
    if (_block) {
        _block(_isPresented);
    }
    return self;
}

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
    return 0.3;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    _isPresented ? [self showAnimateTransition:transitionContext] : [self hiddenAnimateTransition:transitionContext];
    
    
}

- (void)showAnimateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    [transitionContext.containerView addSubview:toView];
    toView.transform = CGAffineTransformMakeScale(1.0, 0.0);
    toView.layer.anchorPoint = CGPointMake(0.5, 0);
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        toView.transform = CGAffineTransformIdentity;
    }completion:^(BOOL finished) {
        [transitionContext completeTransition:TRUE];
    }];
}

- (void)hiddenAnimateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    UIView *fromeView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    fromeView.layer.anchorPoint = CGPointMake(0.5, 0);
    [transitionContext.containerView addSubview:fromeView];
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        fromeView.transform = CGAffineTransformMakeScale(1.0, 0.0001);;
    }completion:^(BOOL finished) {
        [transitionContext completeTransition:TRUE];
    }];
}
@end
